package com.bangdream.michelia.view.activity.currency;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.text.InputType;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bangdream.michelia.R;
import com.bangdream.michelia.contract.UserContract;
import com.bangdream.michelia.entity.UserMsgBean;
import com.bangdream.michelia.presenter.UserPresenter;
import com.bangdream.michelia.tool.StatusBarTool;
import com.bangdream.michelia.utils.MyLog;
import com.bangdream.michelia.utils.PublicUtil;
import com.bangdream.michelia.view.activity.base.BaseActivity;
import com.jaeger.library.StatusBarUtil;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;

/**
 * Created by Mr.Wang on 2018/3/29.
 * 909732184@qq.com
 * 验证码登录
 */

public class CodeLoginActivity extends BaseActivity<UserContract.IUserView,UserPresenter<UserContract.IUserView>>
        implements View.OnClickListener ,UserContract.IUserView{
    private EditText editPhoneNumber,editVerificationCode,editPassWord;
    private TextView btnGetCode,btnGo;
    private static final String TAG = "CodeLoginActivity";
    //是否明文显示密码
    private boolean isShowPassword;
    private View statusBarHeight;
    private RelativeLayout titleBar;
    @Override
    public int getLayout() {
        return R.layout.activity_code_login;
    }

    @Override
    public void findId() {
        editPhoneNumber = findViewById(R.id.editPhoneNumber);
        editVerificationCode = findViewById(R.id.editVerificationCode);
        btnGetCode = findViewById(R.id.btnGetCode);
        btnGo = findViewById(R.id.btnGo);
        editPassWord = findViewById(R.id.editPassWord);
    }

    @Override
    public void logic() {
        /**
         * 设置全屏并且显示状态栏
         */
        //5.0以上系统才支持这个效果 app内容占据导航栏 并且导航栏透明
        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
            //设置状态栏高度（与系统电量栏一样高的占位布局）
            statusBarHeight = findViewById(R.id.statusBarHeight);
            ViewGroup.LayoutParams layoutParams = statusBarHeight.getLayoutParams();
            layoutParams.height = StatusBarTool.getStatusHeight(this);
            statusBarHeight.setLayoutParams(layoutParams);
            titleBar = findViewById(R.id.titleBar);
            titleBar.setBackgroundColor(ContextCompat.getColor(this,R.color.transparent));
        }else {
            StatusBarUtil.setColorNoTranslucent(this, ContextCompat.getColor(this, R.color.text_on));
        }
        initTitleBar(" ","验证码登录","",this);

    }

    @Override
    public UserPresenter createPresenter() {
        UserPresenter presenter = new UserPresenter();
        presenter.setPd(pd);
        return presenter;
    }

    @Override
    public void setListener() {
        btnGetCode.setOnClickListener(this);
        btnGo.setOnClickListener(this);
        editPhoneNumber.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                /*判断是否是“next 下一项”键*/
                if(actionId == EditorInfo.IME_ACTION_NEXT){
                    //点击下一项 密码输入框获取焦点
                    editVerificationCode.requestFocus();
                    return true;
                }
                return false;
            }
        });
        //将输入法切换到英文
        editVerificationCode.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
        editVerificationCode.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                /*判断是否是“GO”键*/
                if(actionId == EditorInfo.IME_ACTION_GO){
                    /*隐藏软键盘*/
                    InputMethodManager imm = (InputMethodManager) v
                            .getContext().getSystemService(
                                    Context.INPUT_METHOD_SERVICE);
                    if (imm.isActive()) {
                        imm.hideSoftInputFromWindow(
                                v.getApplicationWindowToken(), 0);
                    }
                    onClick(btnGo);
                    return true;
                }
                return false;
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btnGo:
                actionCodeLogin();
                break;
            case R.id.btnGetCode:
                if(PublicUtil.isMobileNO(editPhoneNumber.getText().toString())){
                    //获取验证码
                    getVerificationCode();
                }else {
                    showText("请输入正确的手机号");
                }
                break;
            case R.id.tv_left:
                startActivity(new Intent(this,LoginActivity.class));
                finish();
                return;
                default:
                    break;
        }
    }
    //获取验证码
    private void getVerificationCode(){
        mPresenter.getVerificationCode(UserContract.CodeType.LOGINCODE,editPhoneNumber.getText().toString(),pd);
    }

    /**
     * 开始计时 两次获取验证码间隔60秒
     */
    private void stateTime(){
        final long count = 60;
        Observable.interval(0, 1, TimeUnit.SECONDS)         //延时几秒，每隔几秒开始执行
                //超过多少秒停止执行
                .take(count + 1)
                //类型转换，由于是倒计时，案例需要将倒计时的数字反过来
                .map(new Function<Long, Long>() {
                    @Override
                    public Long apply(@NonNull Long aLong) {
                        //MyLog.d("apply",aLong+"=aLong\n"+(count - aLong));
                        return count - aLong;
                    }
                })
                //观察者在主线程执行
                .observeOn(AndroidSchedulers.mainThread())
                //设置订阅观察者
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        MyLog.d(TAG,"执行过程中");
                    }
                })
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        MyLog.d(TAG,"开始执行");
                        seetingButtonState(false);
                    }

                    @Override
                    public void onNext(Long aLong) {
                        MyLog.d(TAG,"剩余" + aLong + "秒");
                        btnGetCode.setText( aLong +"s");
                    }

                    @Override
                    public void onError(Throwable e) {
                        seetingButtonState(true);
                    }

                    @Override
                    public void onComplete() {
                        MyLog.d(TAG,"执行完毕");
                        seetingButtonState(true);
                    }
                });
    }

    /**
     * 设置按钮状态 获取验证码按钮可以点击与不可点击时的两种效果
     */
    private void seetingButtonState(boolean ifOn){
        btnGetCode.setEnabled(ifOn);
        if(ifOn){
            btnGetCode.setText("获取验证码");
            btnGetCode.setBackgroundColor(ContextCompat.getColor(CodeLoginActivity.this,R.color.common_red));
            btnGetCode.setTextColor(ContextCompat.getColor(CodeLoginActivity.this,R.color.white));
        }else {
            btnGetCode.setBackgroundColor(ContextCompat.getColor(CodeLoginActivity.this,R.color.VerificationCodeOff));
            btnGetCode.setTextColor(ContextCompat.getColor(CodeLoginActivity.this,R.color.black_text));
        }
    }

    @Override
    public void setRegisterCode(boolean isSuccess, String stDescribe) {
        if(isSuccess){
            //获取验证码请求成功之后调用开始计时60秒后才能再次获取
            stateTime();
        }else {
            showText(stDescribe+"");
        }
    }

    @Override
    public void actionRegister(boolean isSuccess, String stDescribe) {
        showText(stDescribe);
        if(isSuccess){
            finish();
        }
    }

    @Override
    public void actionLogin(boolean isSuccess, String stDescribe) {
        if(isSuccess){
            Intent intent = new Intent(this,MainActivity.class);
            startActivity(intent);
            finish();
        }else{
            showText(stDescribe);
        }
    }

    @Override
    public void actionFindPassword(boolean isSuccess, String stDescribe) {

    }

    @Override
    public void setUserMsg(boolean isSuccess, UserMsgBean userMsgBean) {

    }

    //找回密码
    private void actionCodeLogin(){
        String stCode = editVerificationCode.getText().toString();
        String stPhone = editPhoneNumber.getText().toString();
        if(checkStrEmpty(stCode,"请输入验证码")
            ||checkStrEmpty(stPhone,"请输入手机号")){
            return;
        }
        mPresenter.actionCodeLogin(stCode,stPhone);
    }

}
